#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>

#include <signal.h>
#include <sys/time.h>
#include <sys/wait.h>

#include "utils.h"

#include "BoseCmd.h"

namespace com {

namespace bose {

int BoseCmd::call_popen(const char * str, char* const outData, int maxBuffSize) {
    FILE *fp;
    int ret = -1, len = 0;

    BOSE_LOGD("FD[%d] call_popen() >>> %s",outData[0], str);
    fp = popen(str, "r");
    if(NULL == fp) {
        BOSE_LOGE("call popen() fp is null!");
        return -1;
    }
    while(fgets(outData + len, maxBuffSize - len, fp) != NULL) {
        len = strlen(outData);
    }
    if(len > 0) ret = 0;
    //BOSE_LOGE("call popen() outData=%s", outData);
    pclose(fp);
    return ret;
}

int BoseCmd::call_system(const char * str, char* const outData, int maxBuffSize) {
    pid_t status;
    int ret = 0;

    BOSE_LOGD("FD[%d] call_system() >>> %s", outData[0], str);
    outData[0] = 0;

    //TODO check str
    if(maxBuffSize > 0) {
        status = system(str);
        if (-1 == status) {
            //BOSE_LOGD("system() error <<< %d", status);
            ret = status;
        } else {
            //BOSE_LOGD("system() exit value=[0x%x]", status);
            ret = WEXITSTATUS(status);
            if (0 != ret){
                BOSE_LOGD("run script fail, script exit code: %d", ret);
            }
        }
    }
    return ret;
}
    
int BoseCmd::sh(const char * str, char* const outData, int maxBuffSize) {

    BOSE_LOGD("FD:%d, process command >>> %s", outData[0], str);
    outData[0] = 0;


    if(str == strstr(str, "popen ")) {
        return call_popen(str + strlen("popen "), outData, maxBuffSize);
    } else if(str == strstr(str, "system ")) {
        return call_system(str, outData, maxBuffSize);
    }

    return 0;
}  //BoseCmd::sh

}  // namespace bose
}  // namespace com
